package com.css.zfzx.sjcj.modules.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.base.response.RestResponse;
import com.css.bpm.platform.org.division.repository.entity.DivisionEntity;
import com.css.bpm.platform.org.user.repository.entity.CertificationEntity;
import com.css.bpm.platform.org.user.repository.entity.UserEntity;
import com.css.bpm.platform.page.login.viewobjects.PwdCheck;
import com.css.bpm.platform.sys.syssubapp.repository.entity.SysSubappEntity;
import com.css.bpm.platform.sys.syssubapp.service.SysSubappService;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformRSAUtils;
import com.css.zfzx.sjcj.cache.DivisionCache;
import com.css.zfzx.sjcj.modules.app.entity.HddcVersionEntity;
import com.css.zfzx.sjcj.modules.app.service.AppLoginService;
import com.css.zfzx.sjcj.modules.app.vo.LoginParamVO;
import com.css.zfzx.sjcj.modules.app.vo.RegistUserVo;
import com.css.zfzx.sjcj.modules.app.vo.UpdatePwdVO;
import com.css.zfzx.sjcj.modules.hddcCjHistorypoints.repository.entity.HddcCjHistorypointsEntity;
import com.css.zfzx.sjcj.modules.hddcCjHistorypoints.service.HddcCjHistorypointsService;
import com.css.zfzx.sjcj.modules.hddccjproject.repository.entity.HddcCjProjectEntity;
import com.css.zfzx.sjcj.modules.hddccjproject.service.HddcCjProjectService;
import com.css.zfzx.sjcj.modules.hddccjproject.viewobjects.HddcCjProjectQueryParams;
import com.css.zfzx.sjcj.modules.hddccjtask.repository.entity.HddcCjTaskEntity;
import com.css.zfzx.sjcj.modules.hddccjtask.service.HddcCjTaskService;
import com.css.zfzx.sjcj.modules.hddccjtask.viewobjects.HddcCjTaskQueryParams;
import com.css.zfzx.sjcj.modules.hddccjtask.viewobjects.HddcCjTaskVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/app")
public class AppController {
    @Autowired
    SysSubappService sysSubappService;
    @Autowired
    AppLoginService appLoginService;

    @Autowired
    private HddcCjTaskService hddcCjTaskService;

    @Autowired
    private HddcCjProjectService hddcCjProjectService;

    @Autowired
    private HddcCjHistorypointsService hddcCjHistorypointsService;

    /**
     * 查询最新版app
     * @param platform
     * @return
     */
    @GetMapping("getVersion")
    public RestResponse getVersion(@RequestParam("platform") String platform) {
        RestResponse restResponse = null;
        try {
            HddcVersionEntity fwVersion=appLoginService.getAppVersion(platform);
            restResponse = RestResponse.succeed(fwVersion);
        } catch (Exception e) {
            String errormessage = "查询失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }
    /***
     * App端登录
     * @param loginParamVO
     * @return
     */
    @PostMapping("/doLogin")
    public RestResponse doLogin(HttpServletRequest request, @RequestBody LoginParamVO loginParamVO) {
        String userName = loginParamVO.getUserName();
        String password = loginParamVO.getPassword();
        String appCode = loginParamVO.getAppCode();

        if (StringUtils.isEmpty(userName)) {
            return RestResponse.fail("用户名不能为空");
        }
        if (StringUtils.isEmpty(password)) {
            return RestResponse.fail("密码不能空");
        }
        if (StringUtils.isEmpty(appCode)) {
            return RestResponse.fail("系统编码不能为空");
        }
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            SysSubappEntity byCode = sysSubappService.findByCode(appCode);
            String privateKey = byCode.getPrivateKey();
            PwdCheck pwdCheck = appLoginService.doLogin(userName, password, privateKey);
            HttpSession session = request.getSession();
            if (pwdCheck.isSuccess()) {
                session.setAttribute("userId", pwdCheck.getUserId());
                session.setAttribute("platform_cur_user_id_in_session", pwdCheck.getUserId());
                response = RestResponse.succeed(pwdCheck);
            } else {
                response = RestResponse.fail(pwdCheck.getErrorMessage());
            }
        } catch (Exception e) {
            String errormessage = "登录失败";
            log.error(errormessage, e);
            response = RestResponse.fail(errormessage);
        }
        return response;
    }


    /***
     * 修改密码
     * @param updatePwdVO
     * @return
     */
    @PostMapping("/updatePwd")
    public RestResponse updatePwd(HttpServletRequest request, @RequestBody UpdatePwdVO updatePwdVO) {
        String ios = request.getHeader("ios");
        RestResponse restResponse = null;
        SysSubappEntity byCode = sysSubappService.findByCode("android");
        String privateKey = null;
        try {
            if ("1".equals(ios)) {
                privateKey = "MIICdAIBADANBgkqhkiG9w0BAQEFAASCAl4wggJaAgEAAoGBAMzvMTloqcyjCDKe" +
                        "g4WovoiRtkPfhbwLfmVRm16dxxYzn8mOR8Xa9BsaBCRk0oSEw7LXn4orkMsjTECn" +
                        "034N3q9AxQZhHz+0fmlJNE8vGuO5wOpuxwaKc/OqnTfKSgRLed9HFTAfbTEqvRBJ" +
                        "VoHf8Q3BxZqoW0eMVsOZc6h8sxdxAgMBAAECf0s/iNOLms2JD3mGusRZMZzz4/kI" +
                        "GhLyJXcOf/498Nw2GHXpyHDd9MP+yYaTfrkqBrGkevBBDumIDHexJ/chIKKQ0nQx" +
                        "qhp5LVZAMwrMjsUaxgHlriqOgMj16tUjvpCC3JXZq7DTyvlDWmQ8bdOWeMotEv/V" +
                        "QNCzf6d7tcqe4yECQQDtyps+C6tnIpIi0EK8STf8Oo68WFQ5ek9aaZnJEn3GnWs2" +
                        "1/W5yBQMajqujlzHIbp9QFdYJSKRQ/Fswic4UXKNAkEA3KB+KDNzPvpQibI6wCn+" +
                        "XLnMQOZahZ7Wy5DGs2Pn3ZKol7ZO0/zN/MC2Cu4aKFZ3oXydcDRhBRy/KPpJ5e/x" +
                        "dQJAJxLg2ZwvSR48Jy5TmP7rDS5OIBLfnCZF/dRWadz4//cEFBn+jc2bxcJ67A4G" +
                        "ns4jB8vXzmsjt/0TIczxhuaTTQJBALrs57Zb0RrcrfvcG9bQPYiGir257ZwkdcxH" +
                        "P3KiBMNADMNtXOBS4ptxE0uzbEoc6ILTt/hnCIRyVKv9UzsTzjkCQG4yE36MH4BC" +
                        "HMoYs6TlWpoDaEuYDksQUzFznVXs1rY2NTI++9AjZ4ZJTVsN2bIWUzm0mkof5x6h" +
                        "yr2dwDFiV2E=";
            } else {
                privateKey = byCode.getPrivateKey();
            }
            String odPwd = PlatformRSAUtils.decrypt(updatePwdVO.getOldPwd(), privateKey);
            String nwPwd = PlatformRSAUtils.decrypt(updatePwdVO.getNewPwd(), privateKey);
            CertificationEntity certificationEntity = PlatformAPI.getOrgAPI().getUserAPI().updateCertification(updatePwdVO.getUserId(), odPwd, nwPwd);
            restResponse = RestResponse.succeed(certificationEntity);
        } catch (Exception e) {
            String errormessage = "修改密码失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /***
     * 查看个人信息
     * @param userId
     * @return
     */
    @GetMapping("/userInfo")
    public RestResponse getUserInfo(@RequestParam("userId") String userId) {
        RestResponse response = null;
        try {
            UserEntity user = PlatformAPI.getOrgAPI().getUserAPI().getUser(userId);
            RegistUserVo registUserVo=new RegistUserVo();
            registUserVo.setDivision(user.getExtend1());
            registUserVo.setIdNumber(user.getIdCard());
            registUserVo.setMobilePhone(user.getMobilePhone());
            registUserVo.setRelName(user.getUserName());
            registUserVo.setUserName(user.getUserName());
            registUserVo.setUnit(user.getExtend2());
            //FwUserEntity fwUserEntity = fwUserService.findByUserId(userId);
            response = RestResponse.succeed(registUserVo);
        } catch (Exception e) {
            String errorMessage = "查询信息失败";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }
    /***
     * 注册app
     */
    @PostMapping("/register")
    public RestResponse registerUser(@RequestBody RegistUserVo registUserVo){
        if (registUserVo == null) {
            return RestResponse.fail("保存用户信息不能为空");
        }
        RestResponse restResponse = null;
        JSONObject json = new JSONObject();
        try{
           String  mobilePhone=registUserVo.getMobilePhone();
           String idCard=registUserVo.getIdNumber();
            if(!StringUtils.isEmpty(mobilePhone)) {
                UserEntity userByCode = PlatformAPI.getOrgAPI().getUserAPI().getValidUserByUserCode(mobilePhone);
                if (userByCode != null) {
                    return RestResponse.fail("手机号已存在");
                }
                List<UserEntity> userEntity = appLoginService.checkIdCard(idCard);
                if (userEntity.size() > 0) {
                    return RestResponse.fail("身份号已存在");
                }
            }
            appLoginService.registUser(registUserVo);
            json.put("message", "注册成功!");
            restResponse=RestResponse.succeed(json);

        }catch (Exception e){
            String errorMessage = "注册失败";
            log.error(errorMessage, e);
            restResponse = RestResponse.fail(errorMessage);
        }
        return restResponse;
    }

    /**
     * 行政区划
     *
     * @return
     */
    @GetMapping("divisions/{divisionid}/subdivisions")
    public RestResponse getDisvion(@PathVariable("divisionid") String divisionId) {
        RestResponse restResponse = null;
        try {
            List<DivisionEntity> subDivisions = PlatformAPI.getDivisionAPI().getSubDivisions(divisionId);
            restResponse = RestResponse.succeed(subDivisions);
        } catch (Exception e) {
            String errormessage = "查询失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }



    @GetMapping("/queryHddcCjTasks")
    public RestResponse queryHddcCjTasks(HttpServletRequest request, HddcCjTaskQueryParams queryParams) {
        RestResponse response = null;
        try{
            int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            String sort= request.getParameter("sort");
            String order= request.getParameter("order");
            JSONObject jsonObject = hddcCjTaskService.queryHddcCjTasks(queryParams, curPage, pageSize, sort, order);
            response = RestResponse.succeed(jsonObject);
        }catch (Exception e){
            String errorMessage = "查询失败!";
            log.error(errorMessage,e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @GetMapping("/queryHddcCjTasksByProjectId")
    public RestResponse queryHddcCjTasksByProjectId(String projectId,int curPage,int pageSize) {
        RestResponse response = null;
        try{
            JSONObject jsonObject = hddcCjTaskService.queryHddcCjTasksByProjectId(projectId, curPage, pageSize);
            response = RestResponse.succeed(jsonObject);
        }catch (Exception e){
            String errorMessage = "查询失败!";
            log.error(errorMessage,e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @GetMapping("/queryAllHddcCjTasks")
    public RestResponse queryAllHddcCjTasks() {
        RestResponse response = null;
        try{
            //int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            //int pageSize = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            List<HddcCjTaskEntity> list = hddcCjTaskService.findAll();
            response = RestResponse.succeed(list);
        }catch (Exception e){
            String errorMessage = "查询失败!";
            log.error(errorMessage,e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @GetMapping("{id}")
    public RestResponse getHddcCjTask(@PathVariable String id) {
        RestResponse response = null;
        try{
            HddcCjTaskVO hddcCjTask = hddcCjTaskService.getHddcCjTask(id);
            response = RestResponse.succeed(hddcCjTask);
        }catch (Exception e){
            String errorMessage = "获取失败!";
            log.error(errorMessage,e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }
    @PostMapping
    public RestResponse saveHddcCjTask(@RequestBody HddcCjTaskEntity hddcCjTask) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try{
            hddcCjTaskService.saveHddcCjTask(hddcCjTask);
            json.put("message", "新增成功!");
            response = RestResponse.succeed(json);
        }catch (Exception e){
            String errorMessage = "新增失败!";
            log.error(errorMessage,e);
            response = RestResponse.fail(errorMessage);
        }
        return response;

    }
    @PutMapping
    public RestResponse updateHddcCjTask(@RequestBody HddcCjTaskEntity hddcCjTask)  {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try{
            hddcCjTaskService.updateHddcCjTask(hddcCjTask);
            json.put("message", "修改成功!");
            response = RestResponse.succeed(json);
        }catch (Exception e){
            String errorMessage = "修改失败!";
            log.error(errorMessage,e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }
    @DeleteMapping
    public RestResponse deleteHddcCjTasks(@RequestParam List<String> ids) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try{

            hddcCjTaskService.deleteHddcCjTasks(ids);
            json.put("message", "删除成功!");
            response = RestResponse.succeed(json);
        }catch (Exception e){
            String errorMessage = "删除失败!";
            log.error(errorMessage,e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @GetMapping("/getValidDictItemsByDictCode/{dictCode}")
    public RestResponse getValidDictItemsByDictCode(@PathVariable String dictCode) {
        RestResponse restResponse = null;
        try {
            restResponse = RestResponse.succeed(hddcCjTaskService.getValidDictItemsByDictCode(dictCode));
        } catch (Exception e) {
            String errorMsg = "字典项获取失败!";
            log.error(errorMsg, e);
            restResponse = RestResponse.fail(errorMsg);
        }
        return restResponse;
    }

    @GetMapping("/findHddcCjTaskEntityByProjectIds/{projectid}")
    public RestResponse findHddcCjTaskEntityByProjectIds(@PathVariable String projectid) {
        RestResponse response = null;
        try{
            List<HddcCjTaskEntity> list = hddcCjTaskService.findHddcCjTaskEntityByProjectIds(projectid);
            response = RestResponse.succeed(list);
        }catch (Exception e){
            String errorMessage = "查询失败!";
            log.error(errorMessage,e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    /**
     * 获取任务编号
     *
     * @return
     */
    @GetMapping("/taskCode/{projectid}")
    public RestResponse getTaskCode(@PathVariable String projectid) {
        RestResponse restResponse = null;
        try {
            String num = DivisionCache.reinforceRWCode(projectid);
            restResponse = RestResponse.succeed(num);
        } catch (Exception e) {
            String errormessage = "获取失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }



    @GetMapping("/queryHddcCjProjects")
    public RestResponse queryHddcCjProjects(HttpServletRequest request, HddcCjProjectQueryParams queryParams) {
        RestResponse response = null;
        try{
            int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            String sort= request.getParameter("sort");
            String order= request.getParameter("order");
            JSONObject jsonObject = hddcCjProjectService.queryHddcCjProjects(queryParams, curPage, pageSize, sort, order);
            response = RestResponse.succeed(jsonObject);
        }catch (Exception e){
            String errorMessage = "查询失败!";
            log.error(errorMessage,e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @GetMapping("/queryHddcCjProjectsByPersonId")
    public RestResponse queryHddcCjProjectsByPersonId(String personId,int curPage,int pageSize) {
        RestResponse response = null;
        try{
            //int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            //int pageSize = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            JSONObject jsonObject = hddcCjProjectService.queryHddcCjProjectsByPersonId(personId, curPage, pageSize);
            response = RestResponse.succeed(jsonObject);
        }catch (Exception e){
            String errorMessage = "查询失败!";
            log.error(errorMessage,e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @GetMapping("/queryAllHddcCjProjects")
    public RestResponse queryAllHddcCjProjects() {
        RestResponse response = null;
        try{
            //int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            //int pageSize = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            List<HddcCjProjectEntity> list = hddcCjProjectService.findAll();
            response = RestResponse.succeed(list);
        }catch (Exception e){
            String errorMessage = "查询失败!";
            log.error(errorMessage,e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    /**
     * 根据人员ID获取对应的项目集合
     * @param personid
     * @return
     */
    @GetMapping("/findHddcCjProjectEntityByPersonId/{personid}")
    public RestResponse findHddcCjProjectEntityByPersonId(@PathVariable String personid){
        RestResponse restResponse=null;
        try{
            List<HddcCjProjectEntity> list = hddcCjProjectService.findHddcCjProjectEntityByPersonId(personid);
            restResponse = RestResponse.succeed(list);
        }catch (Exception e){
            String messsageerror="查询失败";
            restResponse=RestResponse.fail(messsageerror);
        }
        return restResponse;
    }

    /**
     * 获取项目编号
     *
     * @return
     */
    @GetMapping("/projectCode/{areacode}")
    public RestResponse getProjectCode(@PathVariable String areacode) {
        RestResponse restResponse = null;
        try {
            String num = DivisionCache.reinforceXMCode(areacode);
            restResponse = RestResponse.succeed(num);
        } catch (Exception e) {
            String errormessage = "获取失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    @PostMapping("/saveHddcCjHistorypoints")
    public RestResponse saveHddcCjHistorypoints(@RequestBody HddcCjHistorypointsEntity hddcCjHistorypoints) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try{
            hddcCjHistorypointsService.saveHddcCjHistorypoints(hddcCjHistorypoints);
            json.put("message", "新增成功!");
            response = RestResponse.succeed(json);
        }catch (Exception e){
            String errorMessage = "新增失败!";
            log.error(errorMessage,e);
            response = RestResponse.fail(errorMessage);
        }
        return response;

    }
}
